package com.neo.androidcommon.bitmapdemo;

import android.app.ActivityManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.LruCache;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.neo.androidcommon.BaseActivity;
import com.neo.androidcommon.CommonUtils.LogUtil;
import com.neo.androidcommon.R;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/9/11.
 */

public class BitmaoActivity extends BaseActivity {
    @BindView(R.id.bg_img)
    ImageView bgImg;
    @BindView(R.id.crop_img)
    ImageView cropImg;
    @BindView(R.id.save_creen)
    Button saveCreen;
    @BindView(R.id.btn_merory)
    Button btnMerory;
    private ByteArrayOutputStream outputStream;

    @Override
    public int intiLayout() {
        return R.layout.activity_bitmap;
    }

    @Override
    public void initView() {

        try {
            BitmapDrawable bitmapDrawable = new BitmapDrawable(getAssets().open("pic.jpg"));

            Bitmap bitmap = bitmapDrawable.getBitmap();
            bgImg.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }

        cropBitmap();


    }

    private void cropBitmap() {

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.pic);

        Bitmap bitmapShow = Bitmap.createBitmap(bitmap, 200, 200, 200, 200);


        cropImg.setImageBitmap(bitmapShow);

    }

    //通过资源ID
    private Bitmap getBitmapFromResource(Resources res, int resId) {
        return BitmapFactory.decodeResource(res, resId);
    }

    //文件
    private Bitmap getBitmapFromFile(String pathName) {
        return BitmapFactory.decodeFile(pathName);
    }

    //字节数组
    public Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

    //输入流
    private Bitmap getBitmapFromStream(InputStream inputStream) {
        return BitmapFactory.decodeStream(inputStream);
    }

    @Override
    public void initData() {

    }

    @Override
    protected void initListener() {
        saveCreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                captureScreen();
            }


        });

        btnMerory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                Toast.makeText(BitmaoActivity.this, "--最大内存" + manager.getMemoryClass(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void captureScreen() {

        Runnable runnable = new Runnable() {

            private Bitmap bitmap;

            @Override
            public void run() {

                try {


                    View contentView = getWindow().getDecorView();
                    LogUtil.i("高度：" + contentView.getHeight() + ";宽度:" + contentView.getWidth());

                    bitmap = Bitmap.createBitmap(contentView.getWidth(), contentView.getHeight(), Bitmap.Config.ARGB_4444);
                    contentView.draw(new Canvas(bitmap));
                    outputStream = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                    savePic(bitmap, "sdcard/short.png");

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (outputStream != null) {
                        try {
                            outputStream.close();

                            if (bitmap != null && !bitmap.isRecycled()) {

                                bitmap.recycle();
                                bitmap = null;
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }


            }
        };


        try {
            runnable.run();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    private void savePic(Bitmap b, String strFileName) {
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(strFileName);

            if (fos != null) {

                boolean compress = b.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                if (compress) {
                    Toast.makeText(this, "截屏成功", Toast.LENGTH_SHORT).show();
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


//   简单通过SoftReference引用方式管理图片资源

    private Map<String, SoftReference<Bitmap>> imageMap
            = new HashMap<String, SoftReference<Bitmap>>();

    public Bitmap loadBitmap(final String imageUrl, final ImageCallBack imageCallBack) {
        SoftReference<Bitmap> reference = imageMap.get(imageUrl);
        if (reference != null) {
            if (reference.get() != null) {
                return reference.get();
            }
        }
        final Handler handler = new Handler() {
            @Override
            public void handleMessage(final android.os.Message msg) {
                //加入到缓存中
                Bitmap bitmap = (Bitmap) msg.obj;
                imageMap.put(imageUrl, new SoftReference<Bitmap>(bitmap));
                if (imageCallBack != null) {
                    imageCallBack.getBitmap(bitmap);
                }
            }
        };
        new Thread() {
            public void run() {
                Message message = handler.obtainMessage();
                message.obj = downloadBitmap(imageUrl);
                handler.sendMessage(message);
            }
        }.start();
        return null;
    }

    // 从网上下载图片
    private Bitmap downloadBitmap(String imageUrl) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(new URL(imageUrl).openStream());
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public interface ImageCallBack {
        void getBitmap(Bitmap bitmap);
    }


//    LruCache + sd的缓存方式
//
//    1）要先设置缓存图片的内存大小，我这里设置为手机内存的1/8, 手机内存的获取方式：int MAXMEMONRY = (int) (Runtime.getRuntime() .maxMemory() / 1024);
//
//2）LruCache里面的键值对分别是URL和对应的图片
//
//3）重写了一个叫做sizeOf的方法，返回的是图片数量

    private LruCache<String, Bitmap> mMemoryCache;
    int MAXMEMONRY = (int) (Runtime.getRuntime().maxMemory() / 1024);

    private void LruCacheUtils() {
        if (mMemoryCache == null)
            mMemoryCache = new LruCache<String, Bitmap>(
                    MAXMEMONRY / 8) {
                @Override
                protected int sizeOf(String key, Bitmap bitmap) {
                    // 重写此方法来衡量每张图片的大小，默认返回图片数量。
                    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
                }

                @Override
                protected void entryRemoved(boolean evicted, String key,
                                            Bitmap oldValue, Bitmap newValue) {
                    Log.v("tag", "hard cache is full , push to soft cache");

                }
            };
    }

//    4）下面的方法分别是清空缓存、添加图片到缓存、从缓存中取得图片、从缓存中移除。

//    移除和清除缓存是必须要做的事，因为图片缓存处理不当就会报内存溢出，所以一定要引起注意。

    public void clearCache() {
        if (mMemoryCache != null) {
            if (mMemoryCache.size() > 0) {
                Log.d("CacheUtils",
                        "mMemoryCache.size() " + mMemoryCache.size());
                mMemoryCache.evictAll();
                Log.d("CacheUtils", "mMemoryCache.size()" + mMemoryCache.size());
            }
            mMemoryCache = null;
        }
    }

    public synchronized void addBitmapToMemoryCache(String key, Bitmap bitmap) {
        if (mMemoryCache.get(key) == null) {
            if (key != null && bitmap != null)
                mMemoryCache.put(key, bitmap);
        } else
            Log.w(TAG, "the res is aready exits");
    }

    public synchronized Bitmap getBitmapFromMemCache(String key) {
        Bitmap bm = mMemoryCache.get(key);
        if (key != null) {
            return bm;
        }
        return null;
    }

    /**
     * 移除缓存
     *
     * @param key
     */
    public synchronized void removeImageCache(String key) {
        if (key != null) {
            if (mMemoryCache != null) {
                Bitmap bm = mMemoryCache.remove(key);
                if (bm != null)
                    bm.recycle();
            }
        }
    }


}
